package gdepot

//import org.apache.catalina.User

import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional

@Transactional(readOnly = true)
class CartController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond Cart.list(params), model:[cartInstanceCount: Cart.count()]
    }

    def show(Cart cartInstance) {
        respond cartInstance
    }

    def create() {
        respond new Cart(params)
    }

    @Transactional
    def save(Cart cartInstance) {
        if (cartInstance == null) {
            notFound()
            return
        }

        if (cartInstance.hasErrors()) {
            respond cartInstance.errors, view:'create'
            return
        }

        cartInstance.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'cart.label', default: 'Cart'), cartInstance.id])
                redirect cartInstance
            }
            '*' { respond cartInstance, [status: CREATED] }
        }
    }

    def edit(Cart cartInstance) {
        respond cartInstance
    }

    @Transactional
    def update(Cart cartInstance) {
        if (cartInstance == null) {
            notFound()
            return
        }

        if (cartInstance.hasErrors()) {
            respond cartInstance.errors, view:'edit'
            return
        }

        cartInstance.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'Cart.label', default: 'Cart'), cartInstance.id])
                redirect cartInstance
            }
            '*'{ respond cartInstance, [status: OK] }
        }
    }

    @Transactional
    def delete(Cart cartInstance) {

        if (cartInstance == null) {
            notFound()
            return
        }

        cartInstance.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'Cart.label', default: 'Cart'), cartInstance.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'cart.label', default: 'Cart'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }

    def orderService
    def afterInterceptor=[action: this.&addCartToModel,only:[ 'index','search'] ]


    private def addCartToModel(model){
        model.cart=orderService.prepareCart(session)
    }
    @Transactional
    def addToCart(){
//        if(session.userId && params.goodsId){
        if(session.user && params.goodsId){
            orderService.addToCart(session,params.goodsId)
            flash.message = "成功加入购物车"
        }
        /*redirect action: "index"*/
//        forwardTo()
        redirect controller: 'goods',action: 'index'

    }

    def mineCart(){

        if(session.user){

            def user = session.user
            def cartList = Cart.findAllByUser(user)
            def cartCount = cartList.size()
            redirect action: 'index',params:  [cart:cartList,cartInstanceCount:cartCount]

        }
    }
    @Transactional
    def removeFromCart(){
        def lineItem=LineItem.get(params.id)
        //防止用户随意提交的id
        if (lineItem && lineItem.cart.id==session.cartId){
            lineItem.delete()
        }
        /*  redirect action: "index"*/
//        forwardTo()
        redirect action:'index'
    }
    @Transactional
    def changeItemNumber(){
        def lineItem=LineItem.get(params.id)
        //防止用户随意提交
        if(lineItem && lineItem.cart.id == session.cartId){
            lineItem.properties=params
            if(!lineItem.hasErrors() && lineItem.save(flush: true)){
                println lineItem.itemNumber
                flash.message=message(code: 'lineItem.itNumber.update.success')
            }else{
                flash.message=message(code: 'lineItem.itNumber.update.failed')
            }
        }
        /* redirect action: "index"*/
        redirect action: 'index'
    }

    private void forwardTo() {
        if (params.forwardURI) {
            /*redirect(url:  "http://localhost:9000"+params.forwardURI)*/
            String s = params.forwardURI.toString()
            s = s.substring(s.indexOf('/', 2), s.length())
            println s
            redirect(url: s)
            /*redirect(url:  "http://localhost:9000"+params.forwardURI)*/
//            redirect(uri: params.forward)   //params的forward是空的
        } else {
            redirect action: "index"
        }
    }
}
